// src/pages/chat/index.tsx
import styles from "./styles/styles.module.less";
import Header from "@shared/header";
import Back from "@shared/back";
import GeekIcon from "@shared/geekIcon";
import { io } from "socket.io-client";
import { useEffect, useState } from "react";
import { useTypedSelector } from "@store/index";
import { selectToken } from "@slice/token";
import classNames from "classnames";
import { Socket } from "socket.io-client";
import { useRef } from "react";
interface Message {
    type: "robot" | "user";
    message: string;
  }
export default function Chat() {
    // 获取用户登录凭据
  const token = useTypedSelector(selectToken);
  // 用于存储消息列表
  const [messages, setMessages] = useState<Message[]>([]);
  // 用于存储用户在文本框中输入的内容
  const [message, setMessage] = useState("");
  // 用于保存 socket 实例对象
  const socketRef = useRef<Socket | null>(null);
  // 用于保存滚动容器 DOM 对象
  const scrollContainer = useRef<HTMLUListElement | null>(null);

  // 发送消息
  const sendMessage = () => {
    // 将消息添加到本地消息列表
    setMessages([...messages, { type: "user", message }]);
    // 向服务器端发送消息
    socketRef.current?.emit("message", {
      msg: message,
      timestamp: Date.now() + "",
    });
    // 清空文本框中的消息
    setMessage("");
  };
  // websocket
  useEffect(() => {
    // 建立连接
    const socket = io("http://toutiao.itheima.net", {
      query: {
        token,
      },
      transports: ["websocket"],
    });
    // 保存 socket 实例对象
    socketRef.current = socket;
    // 监听服务端响应信息
    socket.on("message", (response:any) => {
      // 将消息添加到本地消息列表
      setMessages((messages) => [
        ...messages,
        { type: "robot", message: response.msg },
      ]);
    });
    // 监听连接成功
    socket.on("connect", () => {
      console.log("websocket 连接成功");
      // 设置默认消息列表
      setMessages([
        { type: "robot", message: "您好，小智同学为您服务。" },
        { type: "robot", message: "请问有什么可以帮您" },
      ]);
    });
    // // 监听断开连接
    // socket.on("disconnect", () => {
    //   console.log("websocket 断开连接");
    // });
    // 组件销毁时执行
    return () => {
      // 断开连接
      socket.disconnect();
    };
  }, [token]);
  useEffect(() => {
    if (scrollContainer.current === null) return;
    scrollContainer.current.scrollTo({
      top: scrollContainer.current.scrollHeight,
      behavior: "smooth",
    });
  }, [messages]);
  return (
    <div className={styles.chat}>
      <Header title={"小智同学"} left={<Back />} />
      <ul className={styles.content}>
        <li>
          <div className={styles.avatar}>
            <GeekIcon type={"iconbtn_xiaozhitongxue"} />
          </div>
          <div className={styles.say}>亲爱的用户您好，小智同学为您服务。</div>
        </li>
        <li>
          <div className={styles.avatar}>
            <GeekIcon type={"iconbtn_xiaozhitongxue"} />
          </div>
          <div className={styles.say}>请问有什么可以帮您</div>
        </li>
        <li className={styles.customer}>
          <div className={styles.avatar}>
            <img
              src={"http://toutiao.itheima.net/images/user_head.jpg"}
              alt={""}
            />
          </div>
          <div className={styles.say}>你好</div>
        </li>
        {messages.map((item, index) => (
        <li key={index} className={classNames({ [styles.customer]: item.type === "user" })}>
          <div className={styles.avatar}>
            {item.type === "robot" ? (
              <GeekIcon type={"iconbtn_xiaozhitongxue"} />
            ) : (
              <img src={"http://toutiao.itheima.net/images/user_head.jpg"} alt={""} />
            )}
          </div>
          <div className={styles.say}>{item.message}</div>
        </li>
      ))}
      </ul>
      <div className={styles.footer}>
        <div className={styles.edit}>
          <GeekIcon type={"iconbianji"} />
          <input value={message} onChange={(e) => setMessage(e.target.value)} />
        </div>
        <button onClick={sendMessage}>发送</button>
      </div>
    </div>
  );
}